package com.bingbaihanji.core.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author 冰白寒祭
 * @date 2024-05-28 21:49:45
 * @description //DataSource 配置类
 */
@Configuration
public class DataSourceConfig {

    private static final Logger log = LoggerFactory.getLogger(DataSourceConfig.class);

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        InputStream resource = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream("druid.properties");
        Properties properties = new Properties();
        try (dataSource; resource) {
            properties.load(resource);
            dataSource.configFromPropeties(properties);
        } catch (IOException e) {
            log.error("文件路径错误: {}", e.getMessage(), e);
        }
        return dataSource;
    }


    //让 Spring 装载 jdbc 的事务管理器
    //注意：Spring 框架内，事务的 bean 的名称默认取 transactionManager
    //因为这里使用 getTransactionManager 作为获取 bean 的方法名，所以系统会自动取 get 后的内容作为 bean 名称
    //如果你取的名字不是 getTransactionManager 的话，那么就必须使用 @Bean("transactionManager") 注解
    @Bean
    public PlatformTransactionManager getTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
